package io.persimmon.core.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.List;

public class JSONUtil {

    public static final ObjectMapper objectMapper = new ObjectMapper();
    public static final ObjectMapper objectMapperFormat = new ObjectMapper();

    static {
        objectMapperFormat.enable(SerializationFeature.INDENT_OUTPUT);
    }

    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String toJsonFormat(Object object) {
        try {
            return objectMapperFormat.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parse(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseList(String json, Class<T> clazz) {
        // 1. 构建 JavaType：List<User> 的类型描述
        JavaType listType = objectMapper.getTypeFactory()
                .constructCollectionType(List.class, clazz); // 第一个参数：集合类型，第二个参数：泛型类型
        // 2. 转换 JSON 到 List<User>
        try {
            return objectMapper.readValue(json, listType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
